package com.android.dialnowsms;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.PeopleColumns;
import android.provider.Contacts.PhonesColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.TextView;

class ContactListAdapter extends CursorAdapter implements Filterable {
  private ContentResolver mContent;
  
  public ContactListAdapter(Context context, Cursor c) {
    super(context, c);
    mContent = context.getContentResolver();
  }

  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final LayoutInflater inflater = LayoutInflater.from(context);
    final TextView view = (TextView) inflater.inflate(
        android.R.layout.simple_dropdown_item_1line, parent, false);
    view.setText(cursor.getString(5) + cursor.getString(3));
    return view;
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    ((TextView) view).setText(cursor.getString(5) + cursor.getString(3));
  }

  @Override
  public String convertToString(Cursor cursor) {
    String targetNumber = cursor.getString(3);
    targetNumber = targetNumber.replace(" ", "").replace("(0)", "")
    .replace("-","").replace(".", "").replace("(", "").replace(")", "");
    return targetNumber;
  }

  @Override
  public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
    if (getFilterQueryProvider() != null) {
      return getFilterQueryProvider().runQuery(constraint);
    }
    StringBuilder buffer = null;
    String[] args = null;
    if (constraint != null) {
      buffer = new StringBuilder();
      buffer.append(PhonesColumns.NUMBER);
      buffer.append(" != ''");
      buffer.append(" AND ");
      buffer.append("UPPER(");
      buffer.append(PeopleColumns.NAME);
      buffer.append(") GLOB ?");
      args = new String[] { constraint.toString().toUpperCase() + "*" };
    };
    return mContent.query(Contacts.People.CONTENT_URI,
        SMSComposer.PEOPLE_PROJECTION, buffer == null ? null : buffer
            .toString(), args, Contacts.People.DEFAULT_SORT_ORDER);
  }
  
}
